package com.ydd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.constant.MessageConstant;
import com.ydd.dto.SysUserDTO;
import com.ydd.dto.SysUserPageQueryDTO;
import com.ydd.entity.SysRole;
import com.ydd.entity.SysUser;
import com.ydd.exception.LoginNameExistedException;
import com.ydd.mapper.SysRoleMapper;
import com.ydd.mapper.SysUserMapper;
import com.ydd.result.PageResult;
import com.ydd.service.SysUserService;
import com.ydd.utils.CommonUntil;
import com.ydd.vo.SysUserRowInfoVO;
import com.ydd.vo.SysUserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 用户列表分页查询
     *
     * @param sysUserPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQueryList(SysUserPageQueryDTO sysUserPageQueryDTO) {

        // 使用PageHelper实现分页查询
        // 从前端传回来的数据中获取 当前页码和每页显示多少条
        int pageNum = sysUserPageQueryDTO.getPage();
        int pageSize = sysUserPageQueryDTO.getLimit();
        PageHelper.startPage(pageNum, pageSize);

        List<SysUserVO> sysUsers = sysUserMapper.pageQuery(sysUserPageQueryDTO);
        // 全查role
        List<SysRole> listRole = sysRoleMapper.selectAll();

        Map<String, String> mapRole = new HashMap<>();
        listRole.forEach(item -> {
            mapRole.put(item.getId(), item.getName());
        });

        // 遍历所有用户
        sysUsers.forEach(sysUser -> {
            String[] ids = CommonUntil.String2Array(sysUser.getRoleId());
            Map<Integer, String> roleIdMap = new HashMap<>();
            Map<Integer, String> roleNameMap = new HashMap<>();
            if (ids.length > 0){
                for (int i = 0; i < ids.length; i ++) {
                    if (mapRole.get(ids[i]) != null) {
                        roleNameMap.put(i, mapRole.get(ids[i]));
                    }
                    roleIdMap.put(i, ids[i]);
                }
            }
            sysUser.setSysRoleId(roleIdMap);
            sysUser.setRoleName(roleNameMap);
        });

        // 根据前端传回数据查询sysUser分页对象
        Page<SysUserVO> page = (Page<SysUserVO>) sysUsers;


        PageResult pageResult = PageResult.builder()
                .count(page.getTotal())
                .currentPage(pageNum)
                .data(page.getResult())
                .pageSize(pageSize)
                .totalPages(page.getPages())
                .build();

        return pageResult;
    }

    /**
     * 管理员添加
     *
     * @param sysUserDTO
     */

    @Override
    public void addSysUser(SysUserDTO sysUserDTO) {

        // 根据loginName查询数据库，如果有，则返回“用户已存在”
        SysUser loginUser = sysUserMapper.selectByLoginName(sysUserDTO);
        if (loginUser == null){
            // 如果没有，则新建对象
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(sysUserDTO, sysUser);

            // 获取前端传回来的roleId数组
            String[] roleId = sysUserDTO.getRoleId();

            // 拼接字符串数组
            /*
            String roleItem = "";
            String start = "[\"";
            String end = "\"]";
            for (int i = 0; i < roleId.length; i++) {
                if (i == roleId.length-1){
                    roleItem += roleId[i] + end;
                } else {
                    roleItem += roleId[i] + ",";
                }
            }
            String roleIds = start + roleItem;
            sysUser.setRoleId(roleIds);
             */
            // 优化，使用CommonUntil的方法
            String roleIds = CommonUntil.Array2String(roleId);
            sysUser.setRoleId(roleIds);

            // 设置默认数据
            sysUser.setId(UUID.randomUUID().toString());
            sysUser.setDefaultData("1");
            // 使用org.springframework.util.DigestUtils 进行密码加密
            sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUserDTO.getPassword().getBytes()));

            // 调用SysUserMapper添加用户
            sysUserMapper.insert(sysUser);
        } else {
            throw new LoginNameExistedException(MessageConstant.LOGINNAME_EXISTS);
        }

    }

    /**
     * 管理员删除
     *
     * @param id
     */
    @Override
    public void sysUserDelete(String id) {

        // 删除管理员用户
        sysUserMapper.deleteById(id);
    }

    /**
     * 根据id查询管理员详情
     *
     * @param id
     * @return
     */
    @Override
    public SysUserRowInfoVO getById(String id) {
        // 根据id查询用户信息
        SysUser sysUser = sysUserMapper.selectById(id);

        //将查询到的结果封装给 SysUserRowInfoVO对象
        SysUserRowInfoVO sysUserRowInfoVO = new SysUserRowInfoVO();
        BeanUtils.copyProperties(sysUser, sysUserRowInfoVO);

        // 重新封装 roleId字符串
        // 将roleId转换为数组封装给 sysUserRowInfoVO
        String[] roleIds = CommonUntil.String2Array(sysUserRowInfoVO.getRoleId());
        sysUserRowInfoVO.setSysRoleId(roleIds);

        return sysUserRowInfoVO;
    }

    /**
     * 管理员修改
     *
     * @param sysUserDTO
     */
    @Override
    public void update(SysUserDTO sysUserDTO) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, sysUser);
        // 修改状态时不需要roleId
        if (sysUserDTO.getRoleId() != null) {
            String sysRoleIds = CommonUntil.Array2String(sysUserDTO.getRoleId());
            sysUser.setRoleId(sysRoleIds);
        }
        sysUserMapper.update(sysUser);
    }
}
